package gw.com.android.ui.news;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gwtsz.gts2.hx.R;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import gw.com.android.app.AppMain;
import gw.com.android.presenter.http.TopNewsRequest;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2017-11-23.
 */
public class TopNewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Activity mContext;
    private List<TopNewsRequest.TopNewsData> mData;
    private List<String> marked;
    private OnItemClickListener listener;
    private DateFormat myFormat;

    public TopNewsAdapter(Activity context, List<String> marked) {
        this.mContext = context;
        this.marked = marked;
        myFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
    }

    public void updateData(List<TopNewsRequest.TopNewsData> data) {
        this.mData = data;
        notifyDataSetChanged();
    }

    public void appendData(List<TopNewsRequest.TopNewsData> data) {
        if (this.mData == null) {
            mData = data;
        } else {
            if (data != null) {
                mData.addAll(data);
            }
        }
        notifyDataSetChanged();
    }

    public List<String> getNewsIds() {
        if (mData == null || mData.isEmpty()) {
            return null;
        }
        List<String> list = new ArrayList<>();
        for (TopNewsRequest.TopNewsData data : mData) {
            if (data != null) {
                list.add(data.id);
            }
        }
        return list;
    }

    public void addMark(String id) {
        if (marked == null) {
            marked = new ArrayList<>();
        }
        marked.add(id);
    }

    public boolean marked(String id) {
        return marked != null && marked.contains(id);
    }

    public void notifyChangeDelay() {
        AppMain.getApp().getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                notifyDataSetChanged();
            }
        }, 300);
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new SimpleViewHolder(mContext.getLayoutInflater().inflate(R.layout.item_topnews, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        // 填充数据
        SimpleViewHolder mHolder = (SimpleViewHolder) holder;
        TopNewsRequest.TopNewsData item = getItem(position);
        if (item == null) {
            return;
        }
        // 时间戳拿到了，现在解析
        mHolder.tv_create_time.setText(formatTime(item.releaseTime, item.serverTime));

        if (TextUtils.isEmpty(item.remark)) {
            mHolder.tv_title.setText(item.title.replaceFirst("恒信贵金属", ""));
        } else {
            mHolder.tv_title.setText(item.remark);
        }
        if (item.isTop) {
            mHolder.tv_is_top.setVisibility(View.VISIBLE);
        } else {
            mHolder.tv_is_top.setVisibility(View.GONE);
        }
        if (marked != null && marked.contains(item.id)) {
            mHolder.tv_title.setTextColor(0xFFA4A7AC);
        } else {
            mHolder.tv_title.setTextColor(mContext.getResources().getColor(R.color.color_b));
        }
        mHolder.tv_preview.setText(String.valueOf(item.pviewsBase + item.pviews).concat("阅读"));
        if (position == getItemCount() - 1) {
            mHolder.divider.setVisibility(View.GONE);
        } else {
            mHolder.divider.setVisibility(View.VISIBLE);
        }
        //封面
        Glide.with(mContext)
                .load(item.coverImg)
                .placeholder(R.mipmap.a_news_nopic)
                .error(R.mipmap.a_news_nopic)
                .dontAnimate()//防止设置placeholder导致第一次不显示网络图片,只显示默认图片的问题
                .into(mHolder.iv_cover);

        mHolder.contentView.setOnClickListener(new ClickListener(position));
    }


    /**
     * 时间：根据发布时间和服务器时间，假设服务器时间是11月4日。 只对比日期。。。
     * 若发布时间是11月4日，则显示“今天 20:05”
     * 若发布时间是11月3日，则显示“昨天 20:05”
     * 若发布时间是11月2日，则显示“11-02 20:05”
     * 若发布时间是11月1日，则显示“11-01 20:05”
     * 若跨年，则在上一年所有月份前加上年份，显示“2018-12-31 20:05”
     */
    private String formatTime(String timeString, long serverTime) {
        if (!TextUtils.isEmpty(timeString) && serverTime > 0) {
            try {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                Date releaseDate = dateFormat.parse(timeString);//发布时间
                Calendar releaseCalendar = Calendar.getInstance();
                releaseCalendar.setTime(releaseDate);

                Calendar serverCalendar = Calendar.getInstance();
                serverCalendar.setTimeInMillis(serverTime * 1000);

                int releaseYear = releaseCalendar.get(Calendar.YEAR);
                int releaseMonth = releaseCalendar.get(Calendar.MONTH);
                int releaseDay = releaseCalendar.get(Calendar.DAY_OF_MONTH);
                int releaseHour = releaseCalendar.get(Calendar.HOUR_OF_DAY);
                int releaseMinute = releaseCalendar.get(Calendar.MINUTE);

                int serverYear = serverCalendar.get(Calendar.YEAR);
                int serverMonth = serverCalendar.get(Calendar.MONTH);
                int serverDay = serverCalendar.get(Calendar.DAY_OF_MONTH);

                StringBuilder sb = new StringBuilder();
                if (releaseYear != serverYear) {
                    sb.append(clockFormat(releaseYear)).append("-").append(clockFormat(releaseMonth + 1)).append("-").append(clockFormat(releaseDay));
                } else {
                    if (releaseMonth == serverMonth) {
                        int offset = serverDay - releaseDay;
                        if (offset == 0) {
                            sb.append("今天");
                        } else if (offset == 1) {
                            sb.append("昨天");
                        } else {
                            sb.append(clockFormat(releaseMonth + 1)).append("-").append(clockFormat(releaseDay));
                        }
                    } else {
                        sb.append(clockFormat(releaseMonth + 1)).append("-").append(clockFormat(releaseDay));
                    }
                }
                sb.append(" ").append(clockFormat(releaseHour)).append(":").append(clockFormat(releaseMinute));
                return sb.toString();
            } catch (Exception e) {
                Logger.e(e);
            }
        }
        return timeString;
    }

    private String clockFormat(int value) {
        if (value <= 9) {
            return "0".concat(String.valueOf(value));
        }
        return String.valueOf(value);
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    public TopNewsRequest.TopNewsData getItem(int position) {
        if (mData != null && mData.size() > position) {
            return mData.get(position);
        }
        return null;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    private class ClickListener implements View.OnClickListener {

        private final int position;

        ClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.OnItemClicked(TopNewsAdapter.this, v, position);
            }
        }

    }

    public static class SimpleViewHolder extends RecyclerView.ViewHolder {

        private TextView tv_title;
        private TextView tv_create_time;
        private TextView tv_is_top;
        private TextView tv_preview;
        private ImageView iv_cover;
        private View divider;

        private View contentView;

        SimpleViewHolder(final View itemView) {
            super(itemView);
            contentView = itemView;
            tv_title = itemView.findViewById(R.id.tv_title);
            iv_cover = itemView.findViewById(R.id.iv_cover);
            tv_preview = itemView.findViewById(R.id.tv_preview);
            tv_is_top = itemView.findViewById(R.id.tv_is_top);
            tv_create_time = itemView.findViewById(R.id.tv_create_time);
            divider = itemView.findViewById(R.id.divider);
        }
    }

    public interface OnItemClickListener {

        void OnItemClicked(RecyclerView.Adapter adapter, View view, int position);

    }

}